
package com.meis.widget.utils;

import ohos.agp.utils.Point;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONException;
import ohos.utils.zson.ZSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
 * @since 2017/3/28
 */
public final class PointUtils {
    private static final String POINTS = "points";
    private static final String POINT = "point";
    private static final String X = "x";
    private static final String Y = "y";

    private PointUtils() {
        throw new AssertionError();
    }

    public static List<Point> getListPointByResourceJson(Context context, String fileName) throws IOException {
        Resource resource = context.getResourceManager().getRawFileEntry(fileName).openRawFile();
        return getListPointByJson(inputStreamToString(resource));
    }

    public static String inputStreamToString(InputStream inputStream) throws IOException {
        if (inputStream != null) {
            StringBuilder sb = new StringBuilder();
            byte[] data = new byte[4096];
            int len;
            while ((len = inputStream.read(data)) != -1) {
                sb.append(new String(data, 0, len));
            }
            inputStream.close();
            return sb.toString();
        }
        return null;
    }

    public static List<Point> getListPointByJsonInputStream(InputStream inputStream) throws IOException {
        return getListPointByJson(inputStreamToString(inputStream));
    }

    public static List<Point> getListPointByJson(String json) {
        if (json != null) {
            try {
                List<Point> list = new ArrayList<>();
                ZSONObject jsonObject = ZSONObject.stringToZSON(json);
                ZSONArray jsonArray = jsonObject.getZSONObject(POINTS).getZSONArray(POINT);
                int size = jsonArray.size();
                for (int i = 0; i < size; i++) {
                    ZSONObject jsonPoint = jsonArray.getZSONObject(i);
                    Point point = new Point(jsonPoint.getInteger(X), jsonPoint.getInteger(Y));
                    list.add(point);
                }
                return list;
            } catch (ZSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
